import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/utils/util.dart';
import 'package:sainbainu/common/values/assets_subtype_cn.dart';

import 'package:sainbainu/common/widgets/widget.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// 控制器
class ImageUploaderController {
  late void Function() clear;
}

typedef SelectedCallback = void Function(List<AssetEntity> images);

/// 图片上传组件
class ImageUploader extends StatefulWidget {
  final int colNum;
  final double spaceSize;
  final int maxCount;
  final double? maxSize;
  final SelectedCallback selectedCallback;
  final ImageUploaderController controller;
  final AlignmentGeometry? uploadIconAlignment;

  const ImageUploader({
    super.key,
    this.colNum = 5,
    this.spaceSize = 8.0,
    this.maxCount = 10,
    this.maxSize,
    this.uploadIconAlignment = Alignment.centerLeft,
    required this.selectedCallback,
    required this.controller,
  });

  @override
  State<ImageUploader> createState() => _ImageUploaderState();
}

class _ImageUploaderState extends State<ImageUploader> {
  /// 图片
  List<AssetEntity> images = [];

  /// 清空（外部控制器调用）
  void clear() {
    setState(() {
      images = [];
    });
    widget.selectedCallback([]);
  }

  @override
  void initState() {
    super.initState();

    /// 实现控制器的方法
    widget.controller.clear = clear;
  }

  /// 选择图片
  void handleChooseImages() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: widget.maxCount,
        selectedAssets: images,
        requestType: RequestType.image,
        previewThumbnailSize: const ThumbnailSize.square(200),
        pathNameBuilder: (path) {
          if (path.isAll) return '最近';
          return AssetsSubtypeCn.cnMap[path.name] ?? path.name;
        },
      ),
    );
    if (result != null) {
      // 过滤图片大小
      var newImages = await Util.filterAssetsEntiteis(
        result,
        maxSize: widget.maxSize,
        onError: (msg) => LoadingUtil.showInfo(msg),
      );
      setState(() {
        images = newImages;
      });
      widget.selectedCallback(newImages);
    }
  }

  /// ios 风格底部选择器
  Future<void> handleShowBottomDialog(AssetEntity ase) async {
    String? res = await showModalActionSheet<String>(
      context: Get.context!,
      style: AdaptiveStyle.iOS,
      actions: [
        SheetAction(
          key: 'preview',
          label: '预览'.tr,
        ),
        SheetAction(
          key: 'remove',
          label: '删除'.tr,
          isDestructiveAction: true,
        ),
      ],
    );
    if (res == 'preview') {
      handlePreviewImage(ase);
    } else if (res == 'remove') {
      handleRemoveImage(ase);
    }
  }

  /// 图像删除
  void handleRemoveImage(AssetEntity ase) {
    images.removeWhere((AssetEntity item) {
      return item.id == ase.id;
    });
    widget.selectedCallback(images);
    setState(() {
      images = images;
    });
  }

  /// 预览图像
  void handlePreviewImage(AssetEntity ase) {
    int index = images.indexOf(ase);
    Get.to(
      () => PhotoViewSaver(
        images: images,
        index: index,
        enableDownload: false,
      ),
      transition: Transition.fadeIn,
      fullscreenDialog: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraint) {
      /// 每一项的尺寸
      double itemSize =
          (constraint.maxWidth - (widget.spaceSize * 4)) / widget.colNum;

      /// 计算容器高度
      double boxHeight = 0;
      if (images.length < widget.colNum) {
        boxHeight = itemSize;
      } else {
        boxHeight = itemSize * 2 + widget.spaceSize;
      }

      /// 选择的图片列表
      List<Widget> imgList = images.map((AssetEntity ase) {
        return InkWell(
          onTap: () => handleShowBottomDialog(ase),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(6),
            child: SizedBox(
              width: itemSize,
              height: itemSize,
              child: AssetEntityImage(
                ase,
                isOriginal: false,
                fit: BoxFit.cover,
              ),
            ),
          ),
        ) as Widget;
      }).toList();

      /// 判断是否显示选择按钮
      if (imgList.length < widget.maxCount) {
        imgList.add(SizedBox(
          width: itemSize,
          height: itemSize,
          child: _buildUploadButton(),
        ));
      }
      return AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        height: boxHeight,
        child: Wrap(
          spacing: widget.spaceSize,
          runSpacing: widget.spaceSize,
          children: imgList,
        ),
      );
    });
  }

  /// 图片选择按钮
  Widget _buildUploadButton() {
    return GestureDetector(
      onTap: () => handleChooseImages(),
      child: Container(
        alignment: widget.uploadIconAlignment,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6),
        ),
        child: Image.asset(
          'assets/images/input-image.png',
          width: 24,
          height: 24,
        ),
      ),
    );
  }
}
